package com.itheima.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserMapper;
import com.itheima.domain.po.User;
import com.itheima.domain.vo.AddUser;
import com.itheima.domain.vo.PageResult;
import com.itheima.domain.vo.QueryPageBean;
import com.itheima.domain.vo.UpdateUser;
import com.itheima.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper mapper;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        //设置分页数据
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<User> list = mapper.findUserByPage(queryPageBean);
        PageInfo<User> pageInfo = new PageInfo<>(list);
//        Long total = mapper.findUserTotal(queryPageBean);
        //3. 结果封装
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }
    @Override
    public boolean addUser(AddUser au) {
        //	I. 在t_user表中添加用户信息 (主键回填)
        int count1 = mapper.addUser(au);
        //  II.  在t_user_role添加该用户的角色信息
        int count2 = mapper.addRoleByUid(au.getId(),au.getRoleIds());
        return count1 != 0 && count2 != 0;
    }
    @Override
    public boolean updateUser(UpdateUser uu) {
        //2). 修改t_user_role表 : 先删除再添加
        if (!CollectionUtils.isEmpty(uu.getRoleIds())) {
            mapper.deleteRoleByUid(uu.getId());
            mapper.addRoleByUid(uu.getId(), uu.getRoleIds());
        }
        //1). 修改t_user表
        int flag = mapper.updateUser(uu);
        return flag >0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        //用户可能没有角色信息
        mapper.deleteRoleByUid(id);
       int flag=mapper.deleteUserById(id);
       return flag >0;
    }
}
